package com.tydic.springboot.config;

import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.tydic.springboot.mapper.admindb"}, sqlSessionFactoryRef = "admindbSqlSessionFactory")
public class AdminDBDataSourceConfig {

    @Value("spring.datasource.db1.username")
    private String useranme;

    @Value("spring.datasource.db1.password")
    private String password;

    @Value("spring.datasource.db1.driver-class-name")
    private String driverClassName;

    @Value("spring.datasource.db1.url")
    private String jdbcUrl;

    @Bean(name = "admindbDataSource")
    public DataSource admindbDataSource() {
        MysqlXADataSource xaDataSource = new MysqlXADataSource();
        xaDataSource.setUrl(jdbcUrl);
        xaDataSource.setUser(useranme);
        xaDataSource.setPassword(password);
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();

        return null;
    }

    @Bean(name = "admindbSqlSessionFactory")
    public SqlSessionFactory admindbSqlSessionFactory(@Qualifier("admindbDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean(name = "admindbSqlSessionTemplate")
    public SqlSessionTemplate admindbSqlSessionTemplate(@Qualifier("admindbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
